package com.sx.jys.app.net.inter

import android.content.Intent
import android.util.Log
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ToastUtils
import com.sx.jys.app.framework.MyApp
import com.sx.jys.app.until.AppActivityManager
import com.sx.jys.ui.act.LoginAct
import me.hgj.jetpackmvvm.BuildConfig
import me.hgj.jetpackmvvm.base.appContext
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.IOException

/**
 * 作者　: hegaojian
 * 时间　: 2022/1/13
 * 描述　: token过期拦截器
 */
class TokenOutInterceptor : Interceptor {

    @kotlin.jvm.Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val response = chain.proceed(request)
        return if (response.body() != null && response.body()!!.contentType() != null) {
            val mediaType = response.body()!!.contentType()
            var string = response.body()!!.string()
            if (BuildConfig.DEBUG) {
                Log.i("NetBody", "-->${string}")
            }
            val responseBody = ResponseBody.create(mediaType, string)
            //返回体处理
            if (response.code() != 200) {
                ToastUtils.showShort(string)
            } else {
                var jstr = JSONObject(string)
                if (jstr.has("flag")) {
                    var code = jstr.getString("flag")
                    if ("997".equals(code) || "998".equals(code)) {
                        //登录状态已过期
                        ThreadUtils.getMainHandler().post {
                            AppActivityManager.getInstance().exitHome()
                            val intent = Intent(MyApp.instance, LoginAct::class.java)
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                            MyApp.instance.startActivity(intent)
                        }
                    }
                }
            }
            response.newBuilder().body(responseBody).build()
        } else {
            response
        }
    }
}